package com.polaris.live.common.util

import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.content.res.ColorStateList
import android.graphics.Color
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.MarginLayoutParams
import android.view.Window
import androidx.activity.ComponentActivity
import androidx.annotation.ColorRes
import androidx.appcompat.app.AppCompatActivity
import androidx.cardview.widget.CardView
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ColorUtils
import com.google.android.material.shape.CornerFamily
import com.google.android.material.shape.MaterialShapeDrawable
import com.google.android.material.shape.ShapeAppearanceModel
import com.polaris.live.common.R
import com.polaris.live.common.ext.dp
import com.zhpan.bannerview.annotation.Visibility

/**
 * ViewUtils
 *
 * @author Created by lucas on 2023/10/29 17:34
 */
object ViewUtils {

    /**
     * 设置down事件触发的事件
     */
    fun registerTouchDown(view: View, result: Boolean = false, l: View.OnClickListener) {
        view.setOnTouchListener { v, event ->
            when (event.actionMasked) {
                MotionEvent.ACTION_DOWN -> l.onClick(v)
                MotionEvent.ACTION_UP -> v.performClick()
            }
            result
        }
    }

    /**
     * 设置边距
     *
     * @param view         视图
     * @param leftMargin   左边距
     * @param topMargin    上边距
     * @param rightMargin  右边距
     * @param bottomMargin 下边距
     */
    fun setMargin(
        view: View,
        leftMargin: Int? = null,
        topMargin: Int? = null,
        rightMargin: Int? = null,
        bottomMargin: Int? = null
    ) {
        val lp = view.layoutParams as? MarginLayoutParams ?: return

        lp.leftMargin = leftMargin ?: lp.leftMargin
        lp.topMargin = topMargin ?: lp.topMargin
        lp.rightMargin = rightMargin ?: lp.rightMargin
        lp.bottomMargin = bottomMargin ?: lp.bottomMargin

        view.layoutParams = lp
    }

    /**
     * 获取左边距
     */
    fun getLeftMargin(view: View): Int {
        val lp = view.layoutParams as? MarginLayoutParams ?: return 0

        return lp.leftMargin
    }

    /**
     * 获取顶边距
     */
    fun getTopMargin(view: View): Int {
        val lp = view.layoutParams as? MarginLayoutParams ?: return 0

        return lp.topMargin
    }

    /**
     * 获取右边距
     */
    fun getRightMargin(view: View): Int {
        val lp = view.layoutParams as? MarginLayoutParams ?: return 0

        return lp.rightMargin
    }

    /**
     * 获取底边距
     */
    fun getBottomMargin(view: View): Int {
        val lp = view.layoutParams as? MarginLayoutParams ?: return 0

        return lp.bottomMargin
    }

    /**
     * 从context中获取window
     */
    fun getWindow(context: Context): Window? {
        return when (context) {
            is Activity -> context.window
            is ContextWrapper -> getWindow(context.baseContext)
            else -> null
        }
    }

    /**
     * 从context中获取window，如果获取不到则抛出异常
     */
    fun requireWindow(context: Context): Window {
        return getWindow(context) ?: throw IllegalStateException("context must exist Window")
    }

    /**
     * 获取顶层activity
     */
    fun getTopActivity(context: Context): ComponentActivity? {
        return if (context is ComponentActivity) {
            context
        } else {
            getAliveTopActivity() as? ComponentActivity?
        }
    }

    /**
     * 获取顶部可用的activity
     */
    fun findTopAliveActivity(): Activity? {
        val activities = ActivityUtils.getActivityList()
        for (activity in activities) {
            if (!activity.isFinishing && !activity.isDestroyed) {
                return activity
            }
        }
        return null
    }

    /**
     * 设置cardView的背景，用于dialog的边缘阴影显示
     */
    fun setCardViewBackground(
        cardView: CardView,
        @ColorRes bgColor: Int,
        topLeftCorner: Int? = null,
        topRightCorner: Int? = null,
        bottomLeftCorner: Int? = null,
        bottomRightCorner: Int? = null
    ) {
        //背景
        val shapeAppearanceModel = ShapeAppearanceModel().toBuilder().apply {
            if (topLeftCorner != null) {
                setTopLeftCorner(CornerFamily.ROUNDED, topLeftCorner.toFloat())
            }
            if (topRightCorner != null) {
                setTopRightCorner(CornerFamily.ROUNDED, topRightCorner.toFloat())
            }
            if (bottomLeftCorner != null) {
                setBottomLeftCorner(CornerFamily.ROUNDED, bottomLeftCorner.toFloat())
            }
            if (bottomRightCorner != null) {
                setBottomRightCorner(CornerFamily.ROUNDED, bottomRightCorner.toFloat())
            }
        }
            .build()

        val materialShapeDrawable = MaterialShapeDrawable(shapeAppearanceModel).apply {
            setShadowColor(Color.BLACK)
            fillColor = ColorStateList.valueOf(ColorUtils.getColor(bgColor))
            elevation = if (cardView.elevation > 0) {
                cardView.elevation
            } else {
                10.dp.toFloat()
            }
        }

        cardView.background = materialShapeDrawable
    }

    /**
     * 清除view最终显示状态
     */
    fun cleanViewVisible(view: View) {
        view.setTag(R.id.view_visible_tag, null)
    }

    /**
     * 设置view的最终显示状态
     */
    fun setViewVisible(view: View, @Visibility visibility: Int) {
        view.setTag(R.id.view_visible_tag, visibility)
    }

    /**
     * 获取view的最终显示状态
     */
    fun getViewVisible(view: View): Int? {
        val obj = view.getTag(R.id.view_visible_tag)
        return if (obj is Int) {
            obj
        } else {
            null
        }
    }

    /**
     * 隐藏activity
     *
     * @param activity activity
     */
    fun hideActivity(activity: Activity) {
        val contentLayout = activity.findViewById<ViewGroup>(Window.ID_ANDROID_CONTENT)
        if (contentLayout != null) {
            contentLayout.visibility = View.GONE
        }
    }

    /**
     * activity是否已经被销毁
     */
    fun isContextValid(context: Context?): Boolean {
        var depth = 0
        var lastContext = context
        while (lastContext is ContextWrapper) {
            if (lastContext is Activity) {
                if (lastContext.isFinishing || lastContext.isDestroyed) {
                    return false
                }
            }
            lastContext = lastContext.baseContext

            if (++depth > 5) {
                return false
            }
        }

        return true // 非 Activity 类型的 Context 通常被认为是有效的
    }

    /**
     * 获取有效的activity
     */
    fun getAliveTopActivity(): Activity? {
        val topActivity = ActivityUtils.getTopActivity()
        if (topActivity == null || topActivity.isDestroyed || topActivity.isFinishing) {
            return null
        }
        return topActivity
    }

    /**
     * 获取有效的activity
     */
    fun getAliveTopCompatActivity(): AppCompatActivity? {
        val topActivity = ActivityUtils.getTopActivity()
        if (topActivity == null || topActivity.isDestroyed || topActivity.isFinishing) {
            return null
        }
        return if (topActivity is AppCompatActivity) {
            topActivity
        } else {
            null
        }
    }
}

/**
 * 如果销毁了则回调
 */
fun LifecycleOwner.ifDestroy(action: () -> Unit) {
    lifecycle.ifDestroy(action)
}

/**
 * 如果销毁了则回调
 */
fun Lifecycle.ifDestroy(action: () -> Unit) {
    addObserver(LifecycleEventObserver { _, event ->
        if (event == Lifecycle.Event.ON_DESTROY) {
            action()
        }
    })
}


/**
 * 设置最终显示状态
 */
fun View.setFinalVisibility(@Visibility visibility: Int) {
    ViewUtils.setViewVisible(this, visibility)
    this.visibility = visibility
}
